// ==UserScript==
// @name         bilibili
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       feliks
// @match        https://www.bilibili.com/*
// @icon         https://www.bilibili.com/favicon.ico
// @grant        none
// @require      https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js
// ==/UserScript==

(function () {
    'use strict';

    // 初始化播放速度
    const playbackRates = [1, 1.25, 1.5, 1.75, 2, 2.5, 3, 4];
    const controlContainerStyles = `
        position: absolute;
        width: 80px;
        left: 10px;
        top: 170px;
        z-index: 999;
        padding: 10px 0;
        background: #000;
        border-radius: 5px;
        display: flex;
        flex-direction: column;
    `;
    const buttonStyles = `
        font-size: 12px !important;
        margin: 5px auto;
        width: 50%;
        height: 25px;
        border-radius: 5px;
    `;

    let currentSpeed = localStorage.getItem('playbackRate') || 1;
    let videoElements = document.getElementsByTagName('video');
    let count = 0;
    let timer = null;

    // 更新播放速度
    function updatePlaybackRate(speed) {
        for (const video of videoElements) {
            video.playbackRate = speed;
            video.play();
        }
    }

    // 创建控制按钮容器
    const controlContainer = document.createElement('div');
    controlContainer.style.cssText = controlContainerStyles;

    // 创建播放速度按钮
    playbackRates.forEach(rate => {
        const buttonElement = document.createElement('button');
        buttonElement.innerText = rate;
        buttonElement.style.cssText = buttonStyles;
        buttonElement.dataset.playbackRate = rate;
        buttonElement.addEventListener('click', () => {
            localStorage.setItem('playbackRate', rate);
            updatePlaybackRate(rate);
            highlightButton(rate);
        });
        controlContainer.appendChild(buttonElement);
    });

    // 高亮当前速度按钮
    function highlightButton(rate) {
        const buttons = controlContainer.querySelectorAll('button');
        buttons.forEach(button => {
            if (parseFloat(button.dataset.playbackRate) === rate) {
                button.style.background = '#f00';
                button.style.color = '#fff';
            } else {
                button.style.background = '#fff';
                button.style.color = '#000';
            }
        });
    }

    // 初始化页面
    document.body.appendChild(controlContainer);
    highlightButton(currentSpeed);
    updatePlaybackRate(currentSpeed);

    // 添加播放模式单选框
    function addRadioButton(name, value, label, checked) {
        const div = document.createElement('div');
        div.style.cssText = 'display: flex; align-items: center; flex-direction: column; text-align: center; margin: 5px 0;';
        const radio = document.createElement('input');
        radio.type = 'radio';
        radio.name = name;
        radio.value = value;
        radio.checked = checked;
        radio.style.cssText = 'margin: auto; display: block; width: 12px; height: 12px; cursor: pointer;';
        const labelElement = document.createElement('label');
        labelElement.innerText = label;
        labelElement.style.cssText = 'color: #fff; font-size: 12px; transform: scale(0.8); cursor: pointer;';
        div.appendChild(radio);
        div.appendChild(labelElement);
        controlContainer.appendChild(div);
        return radio;
    }

    const radio1 = addRadioButton('playMode', '1', '长按模式', localStorage.getItem('radio1') === 'true');
    const radio2 = addRadioButton('playMode', '2', '智能模式', localStorage.getItem('radio2') !== 'false');

    // 事件监听
    radio1.addEventListener('click', () => {
        localStorage.setItem('radio1', true);
        localStorage.setItem('radio2', false);
        updatePlaybackRate(1);
        highlightButton(1);
    });
    radio2.addEventListener('click', () => {
        localStorage.setItem('radio1', false);
        localStorage.setItem('radio2', true);
    });

    document.addEventListener('keydown', event => {
        if (event.keyCode >= 48 && event.keyCode <= 57) {
            const speed = event.keyCode - 48 === 3 ? 2.5 : event.keyCode - 48;
            if (radio2.checked || radio1.checked) {
                currentSpeed = speed;
                localStorage.setItem('playbackRate', speed);
                updatePlaybackRate(speed);
                highlightButton(speed);
                if (radio2.checked) {
                    count++;
                    localStorage.setItem('count', count);
                }
            }
        }
    });

    document.addEventListener('keyup', () => {
        if (radio2.checked) {
            if (count === 1) {
                updatePlaybackRate(currentSpeed);
            } else {
                videoElements[0].pause();
            }
            count = 0;
        } else if (radio1.checked) {
            updatePlaybackRate(1);
            highlightButton(1);
        }
    });

    // 拖动功能
    let drag = false;
    let x, y;

    controlContainer.addEventListener('mousedown', e => {
        e.preventDefault();
        drag = true;
        x = e.clientX - controlContainer.offsetLeft;
        y = e.clientY - controlContainer.offsetTop;
    });

    document.addEventListener('mousemove', e => {
        if (drag) {
            controlContainer.style.left = `${e.clientX - x}px`;
            controlContainer.style.top = `${e.clientY - y}px`;
            toggleSpanDisplay();
        }
    });

    document.addEventListener('mouseup', () => {
        drag = false;
    });

    function toggleSpanDisplay() {
        const span = controlContainer.querySelector('span') || createSpan();
        span.style.display = controlContainer.offsetLeft < -50 ? 'block' : 'none';
    }

    function createSpan() {
        const span = document.createElement('span');
        span.innerText = '>';
        span.style.cssText = `
            font-size: 12px;
            color: #fff;
            position: absolute;
            right: 5px;
            height: ${controlContainer.offsetHeight}px;
            line-height: ${controlContainer.offsetHeight}px;
            display: none;
        `;
        controlContainer.appendChild(span);
        span.addEventListener('click', () => {
            const interval = setInterval(() => {
                controlContainer.style.left = `${controlContainer.offsetLeft + 4}px`;
                if (controlContainer.offsetLeft >= 25) {
                    clearInterval(interval);
                    span.style.display = 'none';
                }
            }, 1);
        });
        return span;
    }

    // 监视视频源变化
    setInterval(() => {
        const currentVideoSrc = videoElements[0]?.src;
        if (currentVideoSrc !== localStorage.getItem('videoSrc')) {
            localStorage.setItem('videoSrc', currentVideoSrc);
            if (localStorage.getItem('radio1') === 'true') {
                updatePlaybackRate(1);
            } else {
                updatePlaybackRate(parseFloat(localStorage.getItem('playbackRate')) || 1);
            }
        }
    }, 1000);

})();
